package com.zgm.ch04._4_2;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StopWatch;

public class MethodReplacementDemo {

	static interface StressTestCallback {

		void run(ReplacementTarget target);
			
	}
	
	public static void main(String[] args){
		XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/zgm/ch04/_4_2/_4_2-context.xml"));
		
		StressTestCallback stringCallback = new StressTestCallback(){
			private final String msg = "hello";
			
			public void run(ReplacementTarget target){
				target.formatMessage(msg);
			}
			
			public String toString(){
				return "formatString(String)";
			}
		};
		
		StressTestCallback objectCallback = new StressTestCallback(){
			private final Object msg = new Object();
			
			public void run(ReplacementTarget target){
				target.formatMessage(msg);
			}
			
			public String toString(){
				return "formatObject(Object)";
			}
		};
		
		stressTest(factory, "replacementTarget", stringCallback);
		stressTest(factory, "standardTarget", stringCallback);
		stressTest(factory, "replacementTarget", objectCallback);
		stressTest(factory, "standardTarget", objectCallback);
	}
	
	private static void stressTest(XmlBeanFactory factory, String beanName, StressTestCallback callback){
		ReplacementTarget target = (ReplacementTarget) factory.getBean(beanName);
		callback.run(target);
		
		StopWatch stopWatch = new StopWatch();
		stopWatch.start("方法替换性能测试：");
		
		for(int i = 0; i < 100000; i++){
			callback.run(target);
		}
		
		stopWatch.stop();
		
		System.out.println("10000次调用 " + callback + " on " + beanName + "耗时为："
							+ stopWatch.getTotalTimeMillis() + " ms");
	}
}
